function init() {
	initMenu();
	initReplyForm();
	initMailForm();
	initOverviewCutOff();
	initPostBackSelects();
	initActions();
	initSmileys();
	initShowMe();
}

function initActions() {
	var action = function () {
		if($(this).is('.urlMe')) {
			window.location = $(this).attr('data-value');
		} else if($(this).is('.url-actionMe')) {
			window.location += $(this).attr('data-value');	
		}
	}
	$('#actionpane option').click(action);
	$('#major_actions input[type="button"], #major_actions button').click(action);
}

function initReplyForm() {
	if($('#rf').length <= 0)
		return;

	var replyForm = $('#rf').hide();

	addReplyToMajorActions('replies', 'reply');

	var openReplyForm = function() {
		if ($(this).parents('.reply').length > 0) {
			replyForm.find('#title').attr('value', $(this).parents(".reply").find(".replytitle").text());
			replyForm.find('textarea.sizedformels')
					 .attr('value', '<quote>' + $(this).parents(".reply").find(".replybeef > .body").text() + '</quote>');
		}
		replyForm.show();	
	}
	$('.replyMe').click(openReplyForm);
}

function addReplyToMajorActions(divId, actionType) {
	if($('#' + divId).length <= 0)
		return;

	var majorActions = $('div#major_actions');
	if(majorActions.length <= 0) {
		majorActions = $('<div id="major_actions"></div>');
		$('#menu').after(majorActions);
	}

	majorActions.append($('<input type="button" class="' + actionType + 'Me" value="reageer" />'));
	$('select#actionpane').append($('<option class="' + actionType + 'Me" >reageer op dit item</option>'));
}

function initMailForm() {
	if($('#mf').length <= 0)
		return;

	var mailForm = $('#mf').hide();

	addReplyToMajorActions('mails', 'mail');

	var mailMes = $('.mailMe');
	var groupMailMes = $('.groupMailMe');
	if(mailMes.length + groupMailMes.length <= 0)
		return;

	var openMailForm = function(subject, to, msg) {
		mailForm.find('#subject').attr('value', subject);
		mailForm.find('#to').attr('value', to);
		if(msg != 'undefined' && !!msg) {
			mailForm.find('#body').html(msg);
		}
		mailForm.show();
	}

	var initMailGroup = function() {
		var groups = $(this).parents('.group');
		if(groups.length <= 0) {
			return;
		}
		groups = groups.eq(0);
	   var members = [];
	   groups.find('.member').each(function() { members.push($(this).text()); });
	   var mailButton = $('<input type="button" value="mail" />');
	   mailButton.click(function() { openMailForm('', members.join(',')); });
		$(this).append(mailButton);
	}

	var initMailReply = function() {
		if($('#mails').length > 0) {
			var to = $('#mails .reply .replyleft > dt > a').text();
			var subject = $('#mails .reply .replytitle').text();
			openMailForm(subject, to);
		}
		else if($(this).is('[data-to]') || $(this).is('[data-subject]')) {
			var to = '';
			if($(this).attr('data-to').match("^#")) {
				var members = $($(this).attr('data-to') + ' .member');	
				members.each(function() { to += (to == '' ? '' : ',') + $(this).html(); });
			}
			else {
				to = $(this).attr('data-to');
			}
			var subject = $(this).attr('data-subject');
			var msg = $(this).is('[data-msg]') ? $(this).attr('data-msg') : '';
			openMailForm(subject, to, msg);
		}
		else if ($(this).parents('.reply').length > 0) {
			 var subject = "je bericht '" + $(this).parents(".reply").find(".replytitle").text() + "'";
			 var to = $(this).parents(".reply").find('.replyleft > dt > a').text();
			 openMailForm(subject, to);
		}
	}

	mailMes.click(initMailReply);
	groupMailMes.each(initMailGroup);
}

function initSmileys() {
	var smileys = [
		{ group: 0, text : '<strong>vet</strong>', surround: ["<b>", "</b>"] },
		{ group: 0, text : '<em>cursief</em>', surround: ["<i>", "</i>"] },
		{ group: 0, text : '<span class=\"marker\">gemarkeerd</span>', surround: ["<marked>", "</marked>"] },
		{ group: 0, text : 'titel', surround: ["<h3>", "</h3>"] },
		{ group: 0, text : 'link', prompt: "link naar deze URL:", surround: ['<a href="{}">', '</a>'] },
		{ group: 0, text : 'alinea', surround: ["<p>", "</p>"] },
		{ group: 1, image : 'smile', add : ":-)" },
		{ group: 1, image : 'wink', add : ";-)" },
		{ group: 1, image : 'tongue', add : ":-p" },
		{ group: 1, image : 'sun', add : "B-)" },
		{ group: 1, image : 'teeth', add : ':-D' },
		{ group: 1, image : 'sad', add : ':-(' },
		{ group: 1, image : 'eek', add : ':eek:' },
		{ group: 1, image : 'sarcastic', add : ':sarcastic:' },
		{ group: 1, image : 'unsure', add : ':unsure:' },
		{ group: 1, image : 'sly', add : ':geniepig:' },
		{ group: 1, image : 'confused', add : ':confused:' },
		{ group: 1, image : 'cry', add : ':cry:' },
		{ group: 1, image : 'blush', add : ':bloos:' },
		{ group: 1, image : 'lol', add : ':lol:' },
		{ group: 1, image : 'angry', add : ':angry:' },
		{ group: 1, image : 'prrrt', add : ':prrrt:' },
		{ group: 1, image : 'yes', add : ':yes:' },
		{ group: 1, image : 'no', add : ':no:' }
	];
	function addSmileys() {
		 var textarea = $(this);
		 var smileyHolders = [];	
		 for (var i = 0; i < smileys.length; i++) {
		 	if(!smileys[i].group) {
				if(smileyHolders.length <= 0)
					smileyHolders.push($('<div class="smileyHolder"></div>'));
			}
			else {
				while(smileyHolders.length <= smileys[i].group) 
					smileyHolders.push($('<div class="smileyHolder"></div>'));
			}
			
			var smile = function() { 
				if($(this).attr('data-surround-head'))
					 inserter.surround(textarea, $(this).attr('data-surround-head'), $(this).attr('data-surround-tail')); 
				if($(this).attr('data-smile'))
					 inserter.replace(textarea, $(this).attr('data-smile')); 
			};
			var addSmiley = function(smiley) { smileyHolders[smileys[i].group].append(smiley); };

			var inserter = new Inserter();

		 	if(!!smileys[i].text) {
				var smiley = $('<button type="button" class="smiley" data-surround-head="' + smileys[i].surround[0]
									+ '" data-surround-tail="' +  smileys[i].surround[1]
									+ '" ></button>').html(smileys[i].text);
				smiley.click(smile);
				addSmiley(smiley);
			}
			else if(!!smileys[i].image) {
				var smiley = $('<button type="button" data-smile="' + smileys[i].add + 
								   '" class="smiley ' + smileys[i].image + 'Smiley"><span>' 
										+ smileys[i].image + "</span></button>");
				smiley.click(smile);
				addSmiley(smiley);
			}
		 }
		 for (var i = smileyHolders.length - 1; i >= 0; i--)
		 	$(this).after(smileyHolders[i]);
	}
	$('#rf textarea').each(addSmileys);
}

function initOverviewCutOff() {

	var addOpenButtons = function () { 
		var visibleRecords = $(this).attr('data-amountVisible') || 10;
		var totalRecords = (visibleRecords * 1) + 1; //force numeric
		var query = 'tr:nth-child(' + totalRecords + ') ~ tr';

		$(this).find('tbody > ' + query ).hide();

		var nrHidden = $(this).find(query).length;

		var openOverview = function() {
			$(this).parents('div.showsubbutton').prev('table.overview').find(query).fadeIn();
			$(this).unbind('click', openOverview).click(closeOverview).text('verberg laatste ' + nrHidden);
		}

		var closeOverview = function() {
			$(this).parents('div.showsubbutton').prev('table.overview').find(query).fadeOut();
			$(this).unbind('click', closeOverview).click(openOverview).text('toon overige ' + nrHidden);
		}
		
		if(nrHidden > 0) {
			var sibling = $(this).next('*').eq(0);

			if(sibling.is('div.showsubbutton')) {
				sibling.append($("<span> - </span>"));
			} else {
				sibling = $('<div class="showsubbutton"></div>');
				$(this).after(sibling);
			}

			var openButton = $('<button type=\"button\" class=\"linkbutton opener closed\">toon overige ' + nrHidden + '</button>').click(openOverview);
			sibling.append(openButton); 
		}
	}

	$('table.overview').each(addOpenButtons);

	if($('.showsubbutton').length > 0)
		addToActions();
}

function addToActions() {

	var toggle = function(item, cssClass, text, oldFunc, newFunc) {
		$('.opener.' + cssClass).click();
		item.text(text).unbind('click', oldFunc).click(newFunc);
	}

	var openAll = function() { 	
		toggle($(this), 'closed', 'verberg alles', openAll, closeAll);
	}

	var closeAll = function() { 	
		toggle($(this), 'open', 'toon alles', closeAll, openAll);
	}

	var showOption = $('<option>toon alles</option>').click(openAll);
	$('select#actionpane').append(showOption);
}

function initPostBackSelects() {
	var selectChange = function () {
		var activeForm = $(this).parents('form').eq(0);
		activeForm.find('input[name="submitted"]').attr('value', 0);
		document.forms[activeForm.attr('name')].submit();
	}
	$('form select.submitMe').change(selectChange);
}

function initMenu() {
	$('.menu_item > .submenu').hide();
	var closeMenu = function() { 
		$(this).find('.submenu').hide(); 
		$(this).removeClass('rightHand');
	};
	var openMenu = function() { 
		if(isOnRightHandSide($(this)))
			 $(this).addClass('rightHand');
		$(this).find('.submenu').show();  
	};
	
	var addClick = function() { 
		if($(this).find('.submenu')) 
			$(this).hover(openMenu, closeMenu);
	}
	$('.menu_item').each(addClick);

	var openCloseMenu = function() {
		$('.menu_item').click();
	}
}

function isOnRightHandSide(elem) {
	return elem.offset().left > ($(document).width() / 2);
}

function initShowMe() {
	$('.showMe[data-value]').click(function() { $('#' + $(this).attr('data-value')).fadeIn(); });
}

function Inserter () {}

Inserter.prototype.add_code = function(obj, mode, code1, code2) {
	var t = obj.jquery ? obj[0] : obj;
	t.focus();

	var get_code = function(mode, code1, code2) {
		if (mode == "REPLACE") 
			return code1;
		return code1 + get_selection() + code2;
	}

	var has_document = function() { return document.selection && document.selection.createRange;} ;
	var get_selection = function() { 
		return has_document() ? document.selection.createRange().text : t.value.substring(t.selectionStart, t.selectionEnd); 
	};
	var insert = function(snip) { 
		if(has_document())
			document.selection.createRange().text = snip; 
		else
		{
			var before = t.value.substring(0, t.selectionStart);
			var after = t.value.substring(t.selectionEnd);
			t.value = before + snip + after; 
		}
	};

	t.focus();
	insert(get_code(mode, code1, code2));
}

Inserter.prototype.replace = function(target, code) {
	this.add_code(target, "REPLACE", code);
}

Inserter.prototype.surround = function(target, heads, tails) {
	this.add_code(target, "SURROUND", heads, tails);
}

$(document).ready(init);
